package com.ken.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ken.constant.MessageConstant;
import com.ken.context.BaseContext;
import com.ken.dto.OrdersPaymentDTO;
import com.ken.dto.OrdersSubmitDTO;
import com.ken.entity.*;
import com.ken.exception.AddressBookBusinessException;
import com.ken.exception.OrderBusinessException;
import com.ken.exception.ShoppingCartBusinessException;
import com.ken.mapper.OrderMapper;
import com.ken.service.*;
import com.ken.vo.OrderPaymentVO;
import com.ken.vo.OrderSubmitVO;
import com.ken.vo.OrderVO;
import com.ken.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ken.constant.MessageConstant.ORDER_NOT_FOUND;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserShoppingCartService userShoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //查询地址
        AddressBook addressBook = addressBookService.getById(ordersSubmitDTO.getAddressBookId());
        //判断是否传入地址
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //获取下单用户
        Long userId = BaseContext.getCurrentId();
        //获取下单用户的当前购物车
        List<ShoppingCart> list = userShoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, userId)
                .list();
        if (list == null && list.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //构造订单
        Orders orders = new Orders();
        BeanUtil.copyProperties(ordersSubmitDTO, orders);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        //存入orders表
        save(orders);
        //把订单详细信息存入order_detail
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = BeanUtil.copyProperties(shoppingCart, OrderDetail.class);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailService.saveBatch(orderDetailList);
        //清除购物车
        userShoppingCartService.remove(
                new LambdaQueryWrapper<ShoppingCart>()
                        .eq(ShoppingCart::getUserId, orders.getUserId()));

        //封装OrderSubmitVO返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
    }

    @Override
    public void repetitionOrderById(Long id) {
        Long userId = BaseContext.getCurrentId();
        List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, id).list();
        // 将订单明细转换为购物车对象（核心数据迁移逻辑）
        List<ShoppingCart> shoppingCartList = list.stream()
                .map(
                        orderDetail -> {
                            ShoppingCart cart = new ShoppingCart();
                            // 排除id字段：保证购物车记录生成新的自增ID
                            BeanUtil.copyProperties(orderDetail, cart, "id");
                            cart.setUserId(userId);
                            cart.setCreateTime(LocalDateTime.now());
                            return cart;
                        }).collect(Collectors.toList());
        userShoppingCartService.saveBatch(shoppingCartList);
    }

    @Override
    public void cancelOrderById(Long id) {
        Orders ordersById = getById(id);
        //订单不存在不能取消
        if (ordersById == null) {
            throw new OrderBusinessException(ORDER_NOT_FOUND);
        }
        //订单已送出不能取消
        if (ordersById.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 创建新的订单对象，用于更新订单状态
        Orders orders = new Orders();
        orders.setId(ordersById.getId());
        // 订单处于待接单状态下取消，调用微信支付接口进行退款
        if (ordersById.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            // 调用微信支付退款接口进行退款
        /*
            weChatPayUtil.refund(
                    orderMapperById.getNumber(), // 商户订单号
                    orderMapperById.getNumber(), // 商户退款单号
                    new BigDecimal(0.01), // 退款金额，单位为元
                    new BigDecimal(0.01)  // 原订单金额
            );
        */
            //修改支付状态为退款状态
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态为“已取消”，并设置取消原因和取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        // 更新数据库中的订单信息
        updateById(orders);
    }

    @Override
    public OrderVO findById(Long id) {
        Orders orders =getById(id);
        List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orders.getId()).list();
        OrderVO orderVO = new OrderVO();
        BeanUtil.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }


    /**
     * 订单支付
     * 该方法处理订单支付逻辑，调用微信支付接口生成预支付交易单，并更新订单状态。
     *
     * @param ordersPaymentDTO 订单支付数据传输对象，包含订单号等支付信息
     * @return 返回订单支付视图对象（OrderPaymentVO），包含支付结果信息
     * @throws Exception 可能抛出的异常，处理支付相关操作时的异常
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 1. 获取当前登录用户ID
        Long userId = BaseContext.getCurrentId();  // 从上下文中获取当前用户的ID
        User user = userService.getById(userId);  // 根据用户ID查询用户信息

        // 2. 调用微信支付接口（注释代码为示例，实际代码被注释掉）
/*
    JSONObject jsonObject = weChatPayUtil.pay(
            ordersPaymentDTO.getOrderNumber(), // 商户订单号
            new BigDecimal(0.01), // 支付金额，单位元
            "苍穹外卖订单", // 商品描述
            user.getOpenid() // 微信用户的openid
    );

    // 3. 判断支付状态，如果订单已支付，则抛出异常
    if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        throw new OrderBusinessException("该订单已支付");  // 如果订单已支付，抛出订单业务异常
    }

    // 4. 将微信支付的返回结果转化为OrderPaymentVO对象
    OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
    vo.setPackageStr(jsonObject.getString("package"));  // 设置支付包信息
*/

        // 5. 模拟支付成功的返回结果（替代微信支付的逻辑）
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");  // 设置支付成功的状态
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));  // 设置支付包信息

        // 6. 更新订单状态：将订单状态更新为已支付，待确认
        Integer OrderPaidStatus = Orders.PAID;  // 订单已支付状态
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  // 订单待确认状态
        LocalDateTime check_out_time = LocalDateTime.now();  // 当前时间作为结算时间
        String orderNumber = ordersPaymentDTO.getOrderNumber();  // 获取订单号

        // 7. 调用订单更新方法，将订单状态更新为已支付并待确认 // 日志记录
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderNumber);  // 更新订单状态
        //通过webSocketServer向管理端浏览器 推送消息  字段包括：type，orderId，content
        Map map=new HashMap();
        map.put("type",1); //1为来单提醒 2为客户催单
        map.put("orderId",user.getId());
        map.put("content","订单号:"+orderNumber);

        String json = JSON.toJSONString(map);
        //TODO webSocketServer
        //webSocketServer.sendToAllClient(json);

        // 8. 返回支付结果视图对象
        return vo;  // 返回支付结果，包含支付信息
    }


    @Override
    public void reminderById(Long id) {
        Orders orders = getById(id);
        if (orders==null){
            throw new OrderBusinessException(ORDER_NOT_FOUND);
        }
        HashMap hashMap = new HashMap();
        hashMap.put("type",2);
        hashMap.put("orderId",id);
        hashMap.put("content","订单号："+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(hashMap));
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        Long userId = BaseContext.getCurrentId();



        // 根据订单号和用户id查询订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo,userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.updateById(orders);

/*        //通过webSocketServer向管理端浏览器 推送消息  字段包括：type，orderId，content
        Map map=new HashMap();
        map.put("type",1); //1为来单提醒 2为客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:"+outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        log.info("来单提醒：{}", JSON.toJSONString(map));*/

    }
}